<?php

/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class AppModel extends Model {

    public $actsAs = array('Containable');

    public function existent($data, $pk) {
        if ($this->exists($data[$pk])) {
            return true;
        }
        return false;
    }

    public function findAll($start = null, $length = null, $order = array(), $filter = array(), $conditions = array(), $contain = array()) {
        $start = (!empty($start)) ? intval($start) : 0;
        $length = (!empty($length)) ? intval($length) : 10;
        $limit = $length;
        $page = (int) (($start + $length) / $limit);
        $order = (!empty($order)) ? $order : array(array('column' => "{$this->name}.{$this->primaryKey}", 'direction' => 'DESC'));

        if (!empty($order)) {
            foreach ($order as $i => $order_detail) {
                $order[$i] = "{$order_detail['column']} {$order_detail['direction']}";
            }
        }

        $where = array();
        if (!empty($filter)) {
            foreach ($filter as $i => $filter_detail) {
                $where[] = array("{$filter_detail['column']} LIKE" => "%{$filter_detail['value']}%");
            }
        }
        $where = array_merge($where, $conditions);

        return $this->find('all', array(
            'conditions' => array(
                $where
            ),
            'order' => $order,
            'limit' => $limit,
            'page' => $page,
            'contain' => $contain
        ));
    }

    public function findCountAll($filter = array(), $conditions = array(), $contain = array()) {
        $where = array();
        if (!empty($filter)) {
            foreach ($filter as $i => $filter_detail) {
                $where[] = array("{$filter_detail['column']} LIKE" => "%{$filter_detail['value']}%");
            }
        }
        $where = array_merge($where, $conditions);

        return $this->find('count', array(
            'conditions' => array(
                $where
            ),
            'contain' => $contain
        ));
    }

}
